import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.activation.MimetypesFileTypeMap;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.web.multipart.MultipartFile;

import com.servicelivedb.ServiceliveDB;
import com.servicelivedb.data.Block;
import com.servicelivedb.data.Customer;
import com.servicelivedb.data.Door;
import com.servicelivedb.data.Items;
import com.servicelivedb.data.Project;
import com.servicelivedb.data.ProjectServiceVendor;
import com.servicelivedb.data.Services;
import com.wavemaker.runtime.RuntimeAccess;
import com.wavemaker.runtime.javaservice.JavaServiceSuperClass;
import com.wavemaker.runtime.server.DownloadResponse;
import com.wavemaker.runtime.server.FileUploadResponse;
import com.wavemaker.runtime.service.annotations.ExposeToClient;

/**
 * This is a client-facing service class. All public methods will be exposed to
 * the client. Their return values and parameters will be passed to the client
 * or taken from the client, respectively. This will be a singleton instance,
 * shared between all requests.
 * 
 * To log, call the superclass method log(LOG_LEVEL, String) or log(LOG_LEVEL,
 * String, Exception). LOG_LEVEL is one of FATAL, ERROR, WARN, INFO and DEBUG to
 * modify your log level. For info on these levels, look for tomcat/log4j
 * documentation
 */
@ExposeToClient
public class FileUploadDownload extends JavaServiceSuperClass {
	/*
	 * Pass in one of FATAL, ERROR, WARN, INFO and DEBUG to modify your log
	 * level; recommend changing this to FATAL or ERROR before deploying. For
	 * info on these levels, look for tomcat/log4j documentation
	 */
	public FileUploadDownload() {
		super(INFO);
	}

	// Constant string
	private String imageFolderPath = "C:\\Softwares\\h2m_images";// "resources/data";
	private String user = "";
	private String password = "";
	private String imageServer;
	private String imageRootDirectory;
	private String imgDirectory;

	public String getImgDirectory() {
		return imgDirectory;
	}

	public void setImgDirectory(String imgDirectory) {
		this.imgDirectory = imgDirectory;
	}

	public String getUser() {
		return user;
	}

	public void setUser(String user) {
		this.user = user;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getImageFolderPath() {
		return imageFolderPath;
	}

	public void setImageFolderPath(String imageFolderPath) {
		this.imageFolderPath = imageFolderPath;
	}

	public String getImageServer() {
		return imageServer;
	}

	public void setImageServer(String imageServer) {
		this.imageServer = imageServer;
	}

	public String getImageRootDirectory() {
		return imageRootDirectory;
	}

	public void setImageRootDirectory(String imageRootDirectory) {
		this.imageRootDirectory = imageRootDirectory;
	}

	/**********************************************************************************
	 * INNER CLASS: WMFile DESCRIPTION: The class WMFile is a class used to
	 * represent information about a list of files. An array of WMFile objects
	 * is returned when the client asks for a list of files on the server.
	 * NOTES: This class can be renamed, and you can add any fields you want (as
	 * long as you add get and set methods for each field). This class is here
	 * as an example, and can be changed to suit your needs
	 **********************************************************************************/
	public class WMFile {
		String path;
		String name;
		long size;
		String type;

		public WMFile(String path, String name, long size, String type) {
			this.path = path;
			this.name = name;
			this.size = size;
			this.type = type;
		}

		public String getPath() {
			return path;
		}

		public void setPath(String s) {
			path = s;
		}

		public String getName() {
			return name;
		}

		public void setName(String s) {
			name = s;
		}

		public String getType() {
			return type;
		}

		public void setType(String s) {
			type = s;
		}

		public long getSize() {
			return size;
		}

		public void setSize(long i) {
			size = i;
		}
	};

	/********************************************************************************
	 * TEMPLATE PROPERTY: uploadDir DESCRIPTION When you created your java
	 * service, you were prompted to enter a value for uploadDir. The uploadDir
	 * is the default location to store files, and any request to delete or
	 * download files that contains a relative path will search for the file
	 * starting from uploadDir. NOTES: You can change this value at any time.
	 * You may need to set a different uploadDir for your deployment environment
	 * than you used on your local development environment.
	 ********************************************************************************/
	String uploadDir = "";

	protected File getUploadDir() {
		uploadDir = RuntimeAccess.getInstance().getSession()
				.getServletContext().getRealPath(imageFolderPath);

		File f = new File(uploadDir);
		f.mkdirs();
		return f;
	}

	protected File getUploadDir(String folderName) {
		uploadDir = RuntimeAccess.getInstance().getSession()
				.getServletContext()
				.getRealPath(imageFolderPath + "/" + folderName);

		File f = new File(uploadDir);
		f.mkdirs();
		return f;
	}

	protected File getSystemUploadDir(String folderName) {

		File f = new File(imgDirectory + "/" + folderName);
		f.mkdirs();
		return f;
	}

	// /
	protected FTPClient getFtpClientForUpload(String folderName)
			throws SocketException, IOException {

		FTPClient ftpClient = getFtpClient();
		ftpClient.changeWorkingDirectory(getImageRootDirectory());
		ftpClient.changeWorkingDirectory("H2MImages");
		// if folder does not exists, create it
		if (!ftpClient.changeWorkingDirectory(folderName)) {
			ftpClient.mkd(folderName);
			ftpClient.changeWorkingDirectory(folderName);
		}

		return ftpClient;
	}

	// /
	protected FTPClient getFtpClient() throws SocketException, IOException {
		FTPClient ftpClient = new FTPClient();
		ftpClient.connect(getImageServer());
		ftpClient.login(getUser(), getPassword());
		return ftpClient;
	}

	/********************************************************************************
	 * NAME: uploadFile DESCRIPTION: The wm.DojoFileUpload widget automatically
	 * calls this method whenever the user selects a new file. RETURNS
	 * DojoFileUploaderResponse This has the following fields Path: tells the
	 * client where the file was stored so that the client can identify the file
	 * to the server Name: tells the client what the original name of the file
	 * was so that any communications with the end user can use a filename
	 * familiar to that user. Type: returns type information to the client,
	 * based on filename extensions (.txt, .pdf, .gif, etc...) Error:This will
	 * NOT trigger an onError, but will allow the user of the widget to scan the
	 * list of returned files for any errors. Width/Height: Intended for
	 * returning width/height of uploaded images, but in fact you can use these
	 * to return any custom information you want. NOTES This is a good starting
	 * point for an upload service. However, there are a number of things you
	 * might want to change 1. File name: you may want to associate a database
	 * index with the filename: 32_hello.png instead of hello.png 2. Folder: you
	 * may want to store files someplace other than uploadDir. Perhaps a folder
	 * named for the table and database index associated with the file. Instead
	 * of uploadDir/hello.png uploadDir/table1/32/hello.png 3. You may actually
	 * want to write the file into a database field 4. You may want to use
	 * uploadDir as a "tmp" folder, and await a second javaservice call before
	 * doing something with the files. Just because a file has uploaded does not
	 * mean that the user has hit "Save" to commit all of their changes. 5. Add
	 * additional parameters that identify the file, what database entry or user
	 * its associated with, and other details of what to do with the file.
	 * (after compiling these changes, you may need to recreate your
	 * wm.DojoFileUpload widget)
	 ********************************************************************************/
	public FileUploadResponse uploadFile(MultipartFile file, String vendorId)
			throws IOException {
		System.out.println("---------------%%%%%%%%%%%%%%%%%%%%%%%%%%%");

		// Create our return object
		FileUploadResponse ret = new FileUploadResponse();
		String imageUrl = "";
		try {
			/* Find our upload directory, make sure it exists */
			String filePath = "vendor_" + vendorId;

			File dir = getSystemUploadDir(filePath);

			if (!dir.exists())
				dir.mkdirs();

			/*
			 * Create a file object that does not point to an existing file.
			 * Loop through names until we find a filename not already in use
			 */
			String filename = file.getOriginalFilename(); /*
														 * .replaceAll(
														 * "[^a-zA-Z0-9 ._-]"
														 * ,"");
														 */
			boolean hasExtension = filename.indexOf(".") != -1;
			String name = (hasExtension) ? filename.substring(0,
					filename.lastIndexOf(".")) : filename;
			String ext = (hasExtension) ? filename.substring(filename
					.lastIndexOf(".")) : "";
			File outputFile = new File(dir, filename);
			for (int i = 0; i < 10000 && outputFile.exists(); i++) {
				outputFile = new File(dir, name + i + ext);
			}

			/* Write the file to the filesystem */
			FileOutputStream fos = new FileOutputStream(outputFile);
			IOUtils.copy(file.getInputStream(), fos);
			file.getInputStream().close();
			fos.close();
			imageUrl = getImageServer()
					+ "services/FileUploadDownload.download?method=downloadFile&fileName="
					+ filePath + "/" + outputFile.getName();
			ret.setPath(imageUrl);

			// Create our return object
			/**
			 * FileUploadResponse ret = new FileUploadResponse(); String
			 * outPutFileName =""; FTPClient ftpClient = null; String folderPath
			 * =""; String imageUrl=""; try { /* Find our upload directory, make
			 * sure it exists
			 */
			/**
			 * folderPath = "vendor_" + vendorId; ftpClient =
			 * getFtpClientForUpload(folderPath);
			 * 
			 * int fileCount = ftpClient.list();
			 * 
			 * /* Create a file object that does not point to an existing file.
			 * Loop through names until we find a filename not already in use
			 */
			/**
			 * String filename = file.getOriginalFilename(); /* .replaceAll(
			 * "[^a-zA-Z0-9 ._-]" ,"");
			 */
			/**
			 * boolean hasExtension = filename.indexOf(".") != -1; String name =
			 * (hasExtension) ? filename.substring(0, filename.lastIndexOf("."))
			 * : filename; String ext = (hasExtension) ?
			 * filename.substring(filename .lastIndexOf(".")) : "";
			 * 
			 * outPutFileName = name + fileCount + ext ;
			 * imageUrl="ftp://"+getUser
			 * ()+":"+getPassword()+"@"+getImageServer()
			 * +"/"+getImageRootDirectory
			 * ()+"/H2MImages/"+folderPath+"/"+outPutFileName;
			 * ftpClient.enterLocalPassiveMode();
			 * ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
			 * 
			 * OutputStream out = ftpClient.storeFileStream(outPutFileName);
			 * 
			 * //boolean isUploaded=
			 * ftpClient.storeFile(outPutFileName,file.getInputStream()); /**
			 * if(out==null){
			 * 
			 * System.out.println("replay strings====================="+
			 * ftpClient.getReplyString());
			 * System.out.println("getReplyCode====================="
			 * +ftpClient.getReplyCode()); }else{
			 * System.out.println(outPutFileName
			 * +"----after storeFileStream--=isUploaded=--------&&&&=");
			 * Util.copyStream(file.getInputStream(), out); out.close();
			 * file.getInputStream().close();
			 * ftpClient.completePendingCommand();
			 * 
			 * //ret.setPath(
			 * "services/FileUploadDownload.download?method=downloadFile&fileName="
			 * +filePath + "/" + outputFile.getName()); /**
			 * System.out.println("outPutFileName==="+outPutFileName); }
			 * ret.setPath(imageUrl); ret.setError(""); ret.setWidth("");
			 * ret.setHeight("");
			 **/
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("ERROR:" + e.getMessage());
			ret.setError(e.getMessage());
		} finally {
			/**
			 * if (ftpClient.isConnected()) { ftpClient.logout();
			 * ftpClient.disconnect(); }
			 **/
			ret.setPath(imageUrl);

		}
		return ret;
	}

	/********************************************************************************
	 * NAME: listFiles DESCRIPTION: Returns a description of every file in the
	 * uploadDir. RETURNS array of inner class WMFile (defined above) NOTES:
	 * This is a rather bare bones implementation. You will likely want to add a
	 * parameter to specify subfolders to list
	 ********************************************************************************/
	public WMFile[] listFiles() throws IOException {
		MimetypesFileTypeMap m = new MimetypesFileTypeMap();
		File dir = getUploadDir();

		/*
		 * Get a list of files; ignore any filename starting with "." as these
		 * are typically private or temporary files not for users to interact
		 * with
		 */
		File[] files = dir.listFiles(new java.io.FilenameFilter() {
			public boolean accept(File dir, String name) {
				return (name.indexOf(".") != 0);
			}
		});

		/* Iterate over every file, creating a WMFile object to be returned */
		WMFile[] result = new WMFile[files.length];
		for (int i = 0; i < files.length; i++) {
			result[i] = new WMFile(files[i].getPath(), files[i].getName(),
					files[i].length(), m.getContentType(files[i]));
		}
		return result;
	}

	/********************************************************************************
	 * NAME: deleteFile/deleteFiles DESCRIPTION: Deletes the files with the
	 * given path or name. If the parameters are just file names, it will look
	 * for files of that name in the uploadDir. If its a full path will delete
	 * the file at that path IF that path is within the uploadDir. RETURNS
	 * nothing, though an error will be noticed by the client. NOTES: -
	 * wm.DojoFileUpload will send a full path, not a relative path to the file
	 * to be deleted. You can change this behavior by changing the path data
	 * sent in the uploadFile method. - These two methods are used by the
	 * wm.DojoFileUpload widget. Renaming these or changing the parameters may
	 * result in a loss of functionality for your upload widget. There are a few
	 * customizations you may still want to make. Of particular note, the test
	 * to verify that its ok to delete the specified file may benefit from a
	 * better understanding of how/where you are storing files.
	 ****************************************************************************/
	public void deleteFiles(String[] files) throws IOException {
		File dir = getUploadDir();
		for (int i = 0; i < files.length; i++) {
			File f = (files[i].startsWith("/")) ? new File(files[i])
					: new File(dir, files[i]);

			// verify that the path specified by the server is a valid path, and
			// not, say,
			// your operating system, or your .password file.
			if (f.getAbsolutePath().indexOf(dir.getAbsolutePath()) == 0)
				f.delete();
		}
	}

	public void deleteFile(String file) throws IOException {
		File dir = getUploadDir();
		File f = (file.startsWith("/")) ? new File(file) : new File(dir, file);

		// verify that the path specified by the server is a valid path, and
		// not, say,
		// your operating system, or your .password file.
		if (f.getAbsolutePath().indexOf(dir.getAbsolutePath()) == 0)
			f.delete();

	}

	/********************************************************************************
	 * NAME: downloadFile DESCRIPTION: The specified file will be downloaded to
	 * the user's computer. - file: filename (if the file is in uploadDir) or
	 * path - filename: Optional string; if used, then this is the name that the
	 * user will see for the downloaded file. Else its name matches whats on the
	 * server. RETURNS DownloadResponse instance NOTES: There are a few
	 * customizations you may still want to make. Of particular note, the test
	 * to verify that its ok to download the specified file may benefit from a
	 * better understanding of how/where you are storing files.
	 ****************************************************************************/
	public DownloadResponse downloadFileNewName(String file, String returnname)
			throws Exception {
		File dir = getUploadDir();
		File f = (file.startsWith("/")) ? new File(file) : new File(dir, file);

		// verify that the path specified by the server is a valid path, and
		// not, say,
		// your .password file.
		if (f.getAbsolutePath().indexOf(dir.getAbsolutePath()) != 0)
			throw new Exception("File not in uploadDir");

		// Create our return object and setup its properties
		DownloadResponse ret = new DownloadResponse();

		returnname = (returnname != null && returnname.length() > 0) ? returnname
				: f.getName();
		String type = new MimetypesFileTypeMap().getContentType(f);
		// Setup the DownloadResponse
		FileInputStream fis = new FileInputStream(f);
		ret.setContents(fis);
		ret.setContentType(type);
		ret.setFileName(returnname);
		return ret;
	}

	public DownloadResponse downloadFile(String fileName) throws Exception {
		DownloadResponse ret = new DownloadResponse();

		String returnname = "";
		File dir = new File(imgDirectory);
		File f = (fileName.startsWith("/")) ? new File(fileName) : new File(
				dir, fileName);
		// File f = new File(file);

		// verify that the path specified by the server is a valid path, and
		// not, say,
		// your .password file.
		if (f.getAbsolutePath().indexOf(dir.getAbsolutePath()) != 0)
			throw new Exception("File not in uploadDir");

		// Create our return object and setup its properties

		try {
			returnname = (returnname != null && returnname.length() > 0) ? returnname
					: f.getName();
			String type = new MimetypesFileTypeMap().getContentType(f);
			// Setup the DownloadResponse
			FileInputStream fis = new FileInputStream(f);
			ret.setContents(fis);
			ret.setContentType(type);
			ret.setFileName(returnname);
			System.out.println("************ DOWNload file is called ::"
					+ fileName);
		} catch (Exception e) {

			e.printStackTrace();
		}
		return ret;
	}

	public String uploadFileToDB(String path, String fileName, Integer itemId) {

		String uploadDir = RuntimeAccess.getInstance().getSession()
				.getServletContext().getRealPath(imageFolderPath);

		ServiceliveDB db = (ServiceliveDB) RuntimeAccess.getInstance()
				.getServiceBean("serviceliveDB");
		// save image into database
		System.out.println("$$$$$$ PATH ==" + path);
		File file = new File(uploadDir + File.separator + fileName);
		byte[] bFile = new byte[(int) file.length()];

		try {
			FileInputStream fileInputStream = new FileInputStream(file);
			// convert file into array of bytes
			fileInputStream.read(bFile);
			fileInputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {

			db.begin();

			Session session = db.getDataServiceManager().getSession();
			// TODO: validations
			Items item = (Items) session.get(Items.class, itemId);

			// item.setImage(bFile);

			session.update(item);

			db.commit();

			// clean up the file if it is success
			file.delete();

		} catch (Exception e) {
			System.out.println(e.getMessage());
		}

		return "success";
	}

	public FileUploadResponse uploadVendorItemList(MultipartFile file,
			String vendorId) throws IOException {
		System.out
				.println(vendorId
						+ "---------------%%%%%%%%%%%%%%%%uploadVendorItemList    %%%%%%%%%%% filename==");

		// Create our return object
		FileUploadResponse ret = new FileUploadResponse();
		String imageUrl = "";
		try {
			/* Find our upload directory, make sure it exists */
			String filePath = "vendor_" + vendorId;

			File dir = new File(imgDirectory);

			if (!dir.exists())
				dir.mkdirs();

			/*
			 * Create a file object that does not point to an existing file.
			 * Loop through names until we find a filename not already in use
			 */
			String filename = file.getOriginalFilename(); /*
														 * .replaceAll(
														 * "[^a-zA-Z0-9 ._-]"
														 * ,"");
														 */
			boolean hasExtension = filename.indexOf(".") != -1;
			String name = (hasExtension) ? filename.substring(0,
					filename.lastIndexOf(".")) : filename;
			String ext = (hasExtension) ? filename.substring(filename
					.lastIndexOf(".")) : "";
			File outputFile = new File(dir, filename);
			for (int i = 0; i < 10000 && outputFile.exists(); i++) {
				outputFile = new File(dir, name + i + ext);
			}

			/* Write the file to the filesystem */
			FileOutputStream fos = new FileOutputStream(outputFile);
			IOUtils.copy(file.getInputStream(), fos);
			file.getInputStream().close();
			fos.close();
			System.out
					.println(vendorId
							+ "---------------%%%%%%%%%%%%%%%%uploadVendorItemList    %%%%%%%%%%% filename=="
							+ filename);
			processVendorItemList(outputFile, vendorId);
			
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("ERROR:" + e.getMessage());
			ret.setError(e.getMessage());
		} finally {

		}
		return ret;
	}

	public FileUploadResponse uploadProjectBlockDoors(MultipartFile file,
			Integer projectId) throws IOException {
		System.out
				.println(projectId
						+ "---------------%%%%%%%%%%%%%%%%uploadProjectBlockDoors    %%%%%%%%%%% filename==");
		ServiceliveDB db = null;
		// Create our return object
		FileUploadResponse ret = new FileUploadResponse();
		String imageUrl = "";
		try {
			/* Find our upload directory, make sure it exists */
			String filePath = "vendor_" + projectId;

			File dir = new File(imgDirectory);

			if (!dir.exists())
				dir.mkdirs();

			/*
			 * Create a file object that does not point to an existing file.
			 * Loop through names until we find a filename not already in use
			 */
			String filename = file.getOriginalFilename(); /*
														 * .replaceAll(
														 * "[^a-zA-Z0-9 ._-]"
														 * ,"");
														 */
			boolean hasExtension = filename.indexOf(".") != -1;
			String name = (hasExtension) ? filename.substring(0,
					filename.lastIndexOf(".")) : filename;
			String ext = (hasExtension) ? filename.substring(filename
					.lastIndexOf(".")) : "";
			File outputFile = new File(dir, filename);
			for (int i = 0; i < 10000 && outputFile.exists(); i++) {
				outputFile = new File(dir, name + i + ext);
			}

			/* Write the file to the filesystem */
			FileOutputStream fos = new FileOutputStream(outputFile);
			IOUtils.copy(file.getInputStream(), fos);
			file.getInputStream().close();
			fos.close();
			System.out
					.println(projectId
							+ "---------------%%%%%%%%%%%%%%%%uploadVendorItemList    %%%%%%%%%%% filename=="
							+ filename);
			db = (ServiceliveDB) RuntimeAccess.getInstance().getServiceBean(
					"serviceliveDB");
			db.begin();

			Session session = db.getDataServiceManager().getSession();
			Project project = (Project) session.get(Project.class, projectId);

			List<Block> blocks = new Excelread().processBlocks(outputFile, project);
			
			StringBuilder output = new StringBuilder("");
			System.out.println("@@@@@@@@@@@@ block size="+blocks.size());
			for (Block block : blocks) {
				session.saveOrUpdate(block);
				int count = 0;
				StringBuilder value = new StringBuilder("");
				for (Door door : block.getDoors()) {
					session.saveOrUpdate(door);

					if (count != 0) {
						value.append(",");

					}
					value.append(door.getDoorName());

					count++;
				}
				output.append("##################{");
				output.append(System.getProperty("line.separator"));
				output.append("\"name\" : \"" + block.getBlockName() + "\",");
				output.append(System.getProperty("line.separator"));
				output.append("\"dataValue\" : \"" + value.toString() + "\"");
				output.append(System.getProperty("line.separator"));
				output.append("},");
			}
			System.out.println("@@@@@@@@@@@@@ output="+output.toString());
			session.saveOrUpdate(project);
			ret.setError("Uploaded succesfully");
			db.commit();
		} catch (Exception e) {
			db.rollback();
			e.printStackTrace();
			System.out.println("ERROR:" + e.getMessage());
			ret.setError(e.getMessage());
		} finally {

		}
		return ret;
	}

	// private void uploadVendorItemList(File outputFile, String vendorId) {
	private void processVendorItemList(File outputFile, String vendorId) throws Exception {

		/**
		 * Read the excel row
		 * 
		 * List<Items> excelItems= create a list of Rows<Items> from excel data.
		 * -- for ( each row ){ : convert the data to Items (Items.java). --map
		 * each property from excel row column
		 * 
		 * }
		 * 
		 * 
		 * 
		 * Now Fetch all Items for a vendor based on the Vendor Id,create a
		 * Map<String,Obj>, i.e Map<Item Name,Items>
		 * 
		 * for (excelItems :Items){
		 * 
		 * get the corresponding Items obj from Map if exist..otherwise add it
		 * to list.
		 * 
		 * If match found then update the same record.
		 * 
		 * continue
		 * 
		 * 
		 * }
		 * 
		 * save/update the list.
		 * 
		 * 
		 */
		/*
		 * System.out.println("outputFile @@ "+outputFile); Project
		 * project=fetchProjectId("National Games Vaillage"); Integer
		 * projId=project.getProjectId();
		 * 
		 * Services services=fetchServiceId("Catering"); Integer
		 * serviceId=services.getServiceId();
		 * 
		 * 
		 * ProjectServiceVendor
		 * psv=fetchPsvId(projId,serviceId,Integer.valueOf(vendorId));
		 * 
		 * Integer projectServiceVendorId=psv.getProjectServiceVendorId();
		 */
		System.out
				.println("****************** Processing vendor Item list start ********************");
		Map<String, Items> vendorItems = fetchVendorItems(Integer
				.valueOf(vendorId));

		// String[] toTest = new String[] {"Idli","Dosa","fgdfg"};
		List<Items> excelItems = new ArrayList();

		ServiceliveDB db = (ServiceliveDB) RuntimeAccess.getInstance()
				.getServiceBean("serviceliveDB");
		Integer result = 0;

		InputStream input = null;

		List<String> errorList = new ArrayList<String>();
		HashSet<Integer> rowIds = new HashSet<Integer>();

		XSSFWorkbook wb = null;
		try {

			db.begin();

			Session session = db.getDataServiceManager().getSession();

			Customer customer = (Customer) session.get(Customer.class,
					Integer.valueOf(vendorId));

			input = new BufferedInputStream(new FileInputStream(outputFile));// "C:/Users/kihegde/Documents/Project/Sprint Phase III/SprintH/ma_mass.xlsx"));
			// XSSFWorkbook wb;

			wb = new XSSFWorkbook(input);
			XSSFSheet sheet = wb.getSheetAt(0);

			// List<itemWorkForce> itemWorkforceList = new
			// ArrayList<itemWorkForce>();
			// sheet.rowIterator();
			Iterator<Row> rows = sheet.rowIterator();
			int rowCount = 0;

			while (rows.hasNext()) {
				System.out.println("Row Number::" + rowCount);
				int cellCount = 0;

				Boolean isEmptyRow = false;
				XSSFRow row = (XSSFRow) rows.next();
				String itemName = null;

				if (rowCount > 0) {

					Items item = new Items();

					/*
					 * String itemId = getStringCellValue(
					 * row.getCell(cellCount++), rowCount, isEmptyRow,
					 * "Item Id", errorList, rowIds, true);
					 * item.setItemId(Integer.valueOf(itemId));
					 */

					itemName = getStringCellValue(row.getCell(cellCount++),
							rowCount, isEmptyRow, "Item Name", errorList,
							rowIds, true);
					item.setItemName(itemName.trim());

					System.out.println("BLANK" + StringUtils.isBlank(itemName));
					/*
					 * if (StringUtils.isBlank(itemName)) { break; }
					 */
					if (StringUtils.isBlank(itemName))
						continue;

					System.out.println("itemName" + itemName);

					String itemDesc = getStringCellValue(
							row.getCell(cellCount++), rowCount, isEmptyRow,
							"Item Description", errorList, rowIds, true);
					item.setItemDesc(itemDesc);
					System.out.println("itemDesc=" + itemDesc);
					boolean outOfStock = getBooleanValue(
							row.getCell(cellCount++), errorList, rowCount,
							isEmptyRow, "Out Of Stock", true, rowIds);
					item.setOutOfStock(outOfStock);
					System.out.println("outOfStock=" + outOfStock);
					BigDecimal price = getBigDecimalCellValue(
							row.getCell(cellCount++), rowCount, isEmptyRow,
							"Price", errorList, rowIds, true);
					item.setPrice(price);
					System.out.println("step1");

					String imageUrl = getStringCellValue(
							row.getCell(cellCount++), rowCount, isEmptyRow,
							"Image Url", errorList, rowIds, false);
					item.setImageUrl(imageUrl);

					boolean active = getBooleanValue(row.getCell(cellCount++),
							errorList, rowCount, false, "Active", isEmptyRow,
							rowIds);
					item.setActive(active);
					System.out.println("Active" + active);
					String itemType = getStringCellValue(
							row.getCell(cellCount++), rowCount, isEmptyRow,
							"Item Type", errorList, rowIds, true);
					item.setItemType(itemType);

					String currency = getStringCellValue(
							row.getCell(cellCount++), rowCount, isEmptyRow,
							"Currency", errorList, rowIds, false);
					item.setCurrency(currency);
					System.out.println("step2");
					BigDecimal tpsShareExl = getBigDecimalCellValue(
							row.getCell(cellCount++), rowCount, isEmptyRow,
							"tpsShareExl", errorList, rowIds, false);
					item.setTpsShareExl(tpsShareExl);

					BigDecimal tpsShareIncl = getBigDecimalCellValue(
							row.getCell(cellCount++), rowCount, isEmptyRow,
							"tpsShareIncl", errorList, rowIds, true);
					item.setTpsShareIncl(tpsShareIncl);

					BigDecimal tpsPercentExl = getBigDecimalCellValue(
							row.getCell(cellCount++), rowCount, isEmptyRow,
							"tpsPercentExl", errorList, rowIds, false);
					item.setTpsPercentExl(tpsPercentExl);

					System.out.println("step3");

					BigDecimal tpsPercentIncl = getBigDecimalCellValue(
							row.getCell(cellCount++), rowCount, isEmptyRow,
							"tpsPercentIncl", errorList, rowIds, false);
					item.setTpsPercentIncl(tpsPercentIncl);

					BigDecimal eduCess = getBigDecimalCellValue(
							row.getCell(cellCount++), rowCount, isEmptyRow,
							"eduCess", errorList, rowIds, true);
					item.setEduCess(eduCess);

					BigDecimal serviceTax = getBigDecimalCellValue(
							row.getCell(cellCount++), rowCount, isEmptyRow,
							"Service Tax", errorList, rowIds, false);
					item.setServiceTax(serviceTax);
					System.out.println("step4");
					BigDecimal vat = getBigDecimalCellValue(
							row.getCell(cellCount++), rowCount, isEmptyRow,
							"Vat", errorList, rowIds, false);
					item.setVat(vat);

					BigDecimal baseValue = getBigDecimalCellValue(
							row.getCell(cellCount++), rowCount, isEmptyRow,
							"Base Value", errorList, rowIds, false);
					item.setBaseValue(baseValue);

					String projectName = getStringCellValue(
							row.getCell(cellCount++), rowCount, isEmptyRow,
							"Project Name", errorList, rowIds, true);

					String serviceName = getStringCellValue(
							row.getCell(cellCount++), rowCount, isEmptyRow,
							"Service Name", errorList, rowIds, true);
					System.out.println("step5");
					BigDecimal vendorPrice = getBigDecimalCellValue(
							row.getCell(cellCount++), rowCount, isEmptyRow,
							"Vendor Price", errorList, rowIds, true);
					item.setVendorPrice(vendorPrice);

					BigDecimal serviceCharge = getBigDecimalCellValue(
							row.getCell(cellCount++), rowCount, isEmptyRow,
							"Service Charge", errorList, rowIds, false);
					item.setServiceCharge(serviceCharge);

					BigDecimal quantity = getBigDecimalCellValue(
							row.getCell(cellCount++), rowCount, isEmptyRow,
							"Quantity", errorList, rowIds, true);
					item.setQuantity(quantity);

					System.out.println("step6");

					BigDecimal minQuantity = getBigDecimalCellValue(
							row.getCell(cellCount++), rowCount, isEmptyRow,
							"Minimum quantity", errorList, rowIds, true);
					item.setMinQuantity(minQuantity);

					String unit = getNumericCellValue(row.getCell(cellCount++),
							rowCount, isEmptyRow, "Unit", errorList, rowIds,
							false);
					item.setUnit(unit);
					System.out.println("step7");
					String otherNames = getStringCellValue(
							row.getCell(cellCount++), rowCount, isEmptyRow,
							"Other Names", errorList, rowIds, true);
					item.setOtherNames(otherNames);

					String updatedBy = getStringCellValue(
							row.getCell(cellCount++), rowCount, isEmptyRow,
							"Updated By", errorList, rowIds, true);
					item.setUpdatedBy(updatedBy);

					System.out.println("step8");
					Date updatedDt = getDateCellFieldValue(
							row.getCell(cellCount++), errorList,
							"Updated Date", isEmptyRow, rowCount, true, rowIds);
					item.setUpdatedDt(updatedDt != null ? (Date) updatedDt
							: null);

					/*
					 * String brand = getStringCellValue(
					 * row.getCell(cellCount++), rowCount,isEmptyRow,"Brand",
					 * errorList, rowIds,true); item.setBrand(brand);
					 */

					BigDecimal discount = getBigDecimalCellValue(
							row.getCell(cellCount++), rowCount, isEmptyRow,
							"Discount", errorList, rowIds, false);
					item.setDiscount(discount);
					// work location

					/*
					 * Date availibilityStartDt = getDateCellFieldValue(
					 * row.getCell
					 * (cellCount++),errorList,"Availability Start Date"
					 * ,isEmptyRow, rowCount, true , rowIds);
					 * 
					 * item.setAvailibilityStartDt(availibilityStartDt != null ?
					 * (Date) availibilityStartDt : null);
					 * 
					 * Date availibilityEndDt = getDateCellFieldValue(
					 * row.getCell
					 * (cellCount++),errorList,"Availibility End Date"
					 * ,isEmptyRow ,rowCount, true , rowIds);
					 * item.setAvailibilityEndDt(availibilityEndDt != null ?
					 * (Date) availibilityEndDt : null);
					 * 
					 * BigDecimal tax = getBigDecimalCellValue(
					 * row.getCell(cellCount++), rowCount, isEmptyRow, "Tax",
					 * errorList, rowIds, false); item.setTax(tax);
					 */

					BigDecimal otherCahrges = getBigDecimalCellValue(
							row.getCell(cellCount++), rowCount, isEmptyRow,
							"Other Charges", errorList, rowIds, false);
					item.setOtherCharges(otherCahrges);

					BigDecimal deliveryChargess = getBigDecimalCellValue(
							row.getCell(cellCount++), rowCount, isEmptyRow,
							"Delivery Charges", errorList, rowIds, false);
					item.setDeliveryCharges(deliveryChargess);

					System.out.println("step9");

					Project project = fetchProjectId(session, projectName);
					Integer projId = project.getProjectId();

					System.out.println("project" + projId);
					if(projId==null)
						throw new Exception("Project not found");

					Services services = fetchServiceId(session, serviceName);
					Integer serviceId = services.getServiceId();
					System.out.println("serviceId" + serviceId);
					if(serviceId==null)
						throw new Exception("Service not found");

					ProjectServiceVendor psv = fetchPsvId(session, projId,
							serviceId, Integer.valueOf(vendorId));
					if (psv == null) {
						continue;
					}
					Integer projectServiceVendorId = psv
							.getProjectServiceVendorId();

					item.setServices(services);
					item.setProjectServiceVendor(psv);
					item.setCustomer(customer);

					System.out.println("isEmptyRow" + isEmptyRow);
					if (!isEmptyRow) {

						System.out.println("add items");
						log(INFO, "Rows validated: " + rowCount);
						System.out.println("item" + item.getItemType());
						excelItems.add(item);

					}

				} else {

				}

				rowCount++;

			}

			// Transaction transaction = session.beginTransaction();
			System.out.println("excelItems.size()" + excelItems.size());
			for (Items item : excelItems) {

				if (vendorItems.containsKey(item.getItemName().toLowerCase())) {
					Integer itemId = vendorItems.get(
							item.getItemName().toLowerCase()).getItemId();

					System.out.println("item id" + itemId);

					item.setItemId(itemId);

					System.out.println("update");
				} else {
					System.out.println("add");
				}

				session.saveOrUpdate(item);

			}
			// transaction.commit();
			db.commit();
		} catch (Exception e) {
			db.rollback();
			System.out.println(e.getMessage());
			
				throw new Exception(e.getMessage());

			/*
			 * result.setMessage("User Not Found");
			 * result.setAuthenticated(false);
			 */

		}

	}

	private Project fetchProjectId(Session session, String projectName) {

		// ServiceliveDB db = (ServiceliveDB) RuntimeAccess.getInstance()
		// .getServiceBean("serviceliveDB");
		Project result = new Project();
		try {
			System.out.println("hello");
			// db.begin();

			// Session session = db.getDataServiceManager().getSession();

			Query query = session
					.createQuery(" from Project project where project.projectName= :projectName");
			query.setString("projectName", projectName);
			System.out.println("QUERY " + query.getQueryString());
			List ProjectList = query.list();

			if (ProjectList != null && !ProjectList.isEmpty()) {
				for (int proj = 0; proj < ProjectList.size(); proj++) {
					Project project = (Project) ProjectList.get(proj);
					System.out.println("$$$$$$$$ project found ::"
							+ project.getProjectId());
					result = project;

				}

			} else {
				System.out.println("itprojectem not found ");
				/*
				 * result.setMessage("User Not Found");
				 * result.setAuthenticated(false);
				 */

			}

			log(INFO, "Returning " + result);

			// db.commit();
		} catch (Exception e) {
			// db.rollback();
			System.out.println(e.getMessage());
			/*
			 * result.setMessage("User Not Found");
			 * result.setAuthenticated(false);
			 */

		}

		return result;

	}

	public Map<String, Items> fetchVendorItems(Integer vendorId) {

		ServiceliveDB db = (ServiceliveDB) RuntimeAccess.getInstance()
				.getServiceBean("serviceliveDB");
		Map result = new HashMap();

		try {
			System.out.println("hello");
			db.begin();

			Session session = db.getDataServiceManager().getSession();

			Query query = session.createQuery(" from Items item where item.customer.customerId= :vendor_id");
			query.setInteger("vendor_id", vendorId);
			System.out.println("QUERY " + query.getQueryString());
			List itemList = query.list();

			if (itemList != null && !itemList.isEmpty()) {
				for (int items = 0; items < itemList.size(); items++) {
					Items item = (Items) itemList.get(items);
					System.out.println("$$$$$$$$ item found ::"
							+ item.getItemName());
					result.put(item.getItemName().toLowerCase(), item);

				}

			} else {
				System.out.println("item not found");
				/*
				 * result.setMessage("User Not Found");
				 * result.setAuthenticated(false);
				 */

			}

			log(INFO, "Returning " + result);

			db.commit();
		} catch (Exception e) {
			db.rollback();
			System.out.println(e.getMessage());
			/*
			 * result.setMessage("User Not Found");
			 * result.setAuthenticated(false);
			 */

		}
		System.out.println("RESULT" + result.size());
		return result;

	}

	private Services fetchServiceId(Session session, String serviceName) {

		// ServiceliveDB db = (ServiceliveDB) RuntimeAccess.getInstance()
		// .getServiceBean("serviceliveDB");
		Services result = new Services();
		try {
			System.out.println("hello");
			// db.begin();

			// Session session = db.getDataServiceManager().getSession();

			Query query = session
					.createQuery(" from Services service where service.serviceName= :serviceName");
			query.setString("serviceName", serviceName);
			System.out.println("QUERY " + query.getQueryString());
			List ServicesList = query.list();

			if (ServicesList != null && !ServicesList.isEmpty()) {
				for (int service = 0; service < ServicesList.size(); service++) {
					Services services = (Services) ServicesList.get(service);
					System.out.println("$$$$$$$$ Services found ::"
							+ services.getServiceId());
					result = services;

				}

			} else {
				System.out.println("Services not found ");
				/*
				 * result.setMessage("User Not Found");
				 * result.setAuthenticated(false);
				 */

			}

			log(INFO, "Returning " + result);

			// db.commit();
		} catch (Exception e) {
			// db.rollback();
			System.out.println(e.getMessage());
			/*
			 * result.setMessage("User Not Found");
			 * result.setAuthenticated(false);
			 */

		}

		return result;

	}

	private ProjectServiceVendor fetchPsvId(Session session, Integer projId,
			Integer serviceId, Integer vendorId) {

		// ServiceliveDB db = (ServiceliveDB) RuntimeAccess.getInstance()
		// .getServiceBean("serviceliveDB");
		ProjectServiceVendor result = null;
		try {
			System.out
					.println("&&&&&&&&&&&&&& values : ************* ==projId="
							+ projId + ";serviceId=" + serviceId
							+ ";customerId=" + vendorId);
			// db.begin();

			// Session session = db.getDataServiceManager().getSession();

			Query query = session
					.createQuery(" from ProjectServiceVendor psv where psv.project.projectId= :projId and psv.services.serviceId= :serviceId and psv.customer.customerId= :customerId");
			query.setInteger("projId", projId);
			query.setInteger("serviceId", serviceId);
			query.setInteger("customerId", vendorId);
			System.out.println("QUERY " + query.getQueryString());
			List ServicesList = query.list();

			if (ServicesList != null && !ServicesList.isEmpty()) {
				for (int service = 0; service < ServicesList.size(); service++) {
					result = (ProjectServiceVendor) ServicesList.get(service);
					System.out.println("$$$$$$$$ Services found ::"
							+ result.getProjectServiceVendorId());

				}

			} else {
				System.out.println("Services not found ");
				/*
				 * result.setMessage("User Not Found");
				 * result.setAuthenticated(false);
				 */

			}

			log(INFO, "Returning " + result);

			// db.commit();
		} catch (Exception e) {
			// db.rollback();
			System.out.println(e.getMessage());
			/*
			 * result.setMessage("User Not Found");
			 * result.setAuthenticated(false);
			 */

		}

		return result;

	}

	private String getStringCellValue(XSSFCell cell, int rowCount,
			Boolean isEmpty, String fieldName, List<String> errorList,
			HashSet<Integer> rowIds, Boolean validate) {
		String cellValue = null;
		try {
			if (cell != null) {
				if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
					cellValue = "";
					if (validate)
						appendToErrorList(errorList, fieldName,
								errorList.size(), rowIds, rowCount);
					return cellValue;
				} else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
					cellValue = cell.getStringCellValue();

					return cellValue;
				} else {
					appendToErrorList(errorList, fieldName, errorList.size(),
							rowIds, rowCount);
				}
			} else {
				if (validate) {
					appendToErrorList(errorList, fieldName, errorList.size(),
							rowIds, rowCount);
				}
			}
		} catch (IllegalStateException exp) {
			appendToErrorList(errorList, fieldName, errorList.size(), rowIds,
					rowCount);
		} catch (NullPointerException e) {
			if (validate) {
				appendToErrorList(errorList, fieldName, errorList.size(),
						rowIds, rowCount);
			}
		} catch (Exception e) {
			log(ERROR, "Exception occured while fetching String cell value.");
		}

		return null;
	}

	private void appendToErrorList(List<String> errorList, String errorMsg,
			int idx, HashSet<Integer> rowIds, int rowCount) {
		try {
			idx = errorList.size() - 1;
			String str = "";
			if (rowIds.contains(rowCount) && idx != -1) {
				if (!errorList.get(idx).contains(errorMsg)) {
					str = errorList.get(idx) + ", " + errorMsg;
					errorList.set(idx, str);
				}
			} else {
				rowIds.add(rowCount);
				errorList.add("Row #" + rowCount + " " + errorMsg);
			}
		} catch (Exception e) {
			log(ERROR, "Exception occured while appending to Error List.");
		}
	}

	private String getNumericCellValue(XSSFCell cell, int rowCount,
			Boolean isEmpty, String fieldName, List<String> errorList,
			HashSet<Integer> rowIds, Boolean validate) {
		Integer cellValue;
		String str = null;
		try {
			if (cell != null) {
				if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
					if (validate)
						appendToErrorList(errorList, fieldName,
								errorList.size(), rowIds, rowCount);
					return null;
				} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
					cellValue = (int) cell.getNumericCellValue();
					return cellValue.toString();
				} else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
					str = cell.getStringCellValue();
					if (!StringUtils.isEmpty(str)) {
						if (str.contains("."))
							str = str.substring(0, str.indexOf("."));
						if (str.matches("^[0-9]+$")) {
							return str;
						} else
							appendToErrorList(errorList, fieldName,
									errorList.size(), rowIds, rowCount);
					} else if (validate) {
						appendToErrorList(errorList, fieldName,
								errorList.size(), rowIds, rowCount);
						return null;
					}

				} else
					appendToErrorList(errorList, fieldName, errorList.size(),
							rowIds, rowCount);
			} else {
				if (validate) {
					appendToErrorList(errorList, fieldName, errorList.size(),
							rowIds, rowCount);
				}
			}

		} catch (IllegalStateException exp) {
			appendToErrorList(errorList, fieldName, errorList.size(), rowIds,
					rowCount);
		} catch (NullPointerException e) {
			if (validate) {
				appendToErrorList(errorList, fieldName, errorList.size(),
						rowIds, rowCount);
			}
		} catch (Exception e) {
			log(ERROR, "Exception occured while fetching Numeric cell value.");
		}

		return null;
	}

	private BigDecimal getBigDecimalCellValue(XSSFCell cell, int rowCount,
			Boolean isEmpty, String fieldName, List<String> errorList,
			HashSet<Integer> rowIds, Boolean validate) {
		BigDecimal returnVal = null;
		Double cellValue = null;
		String str = null;
		try {
			if (cell != null) {
				if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
					if (validate)
						appendToErrorList(errorList, fieldName,
								errorList.size(), rowIds, rowCount);
					return null;
				} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
					cellValue = cell.getNumericCellValue();
					// return cellValue;
				} else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
					str = cell.getStringCellValue();
					try {
						cellValue = new Double(str);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				returnVal = BigDecimal.valueOf(cellValue);
			}

		} catch (IllegalStateException exp) {
			appendToErrorList(errorList, fieldName, errorList.size(), rowIds,
					rowCount);
		} catch (NullPointerException e) {
			if (validate) {
				appendToErrorList(errorList, fieldName, errorList.size(),
						rowIds, rowCount);
			}
		} catch (Exception e) {
			log(ERROR, "Exception occured while fetching Numeric cell value.");
		}

		return returnVal;
	}

	private Date getDateCellFieldValue(XSSFCell cell, List<String> errorList,
			String field, Boolean validate, int rowNo, Boolean isEmpty,
			HashSet<Integer> rowIds) {
		String errorMsg = "";
		int idx = rowIds.size() - 1;
		try {
			if (cell != null) {
				if (cell.getDateCellValue() != null) {
					isEmpty = false;
					return cell.getDateCellValue();
				} else {
					if (validate) {
						appendToErrorList(errorList, field, idx, rowIds, rowNo);
					}
				}

			} else {
				if (validate) {
					appendToErrorList(errorList, field, idx, rowIds, rowNo);
				}
			}

		} catch (IllegalStateException exp) {
			errorMsg = " " + field + " format (Expected: mm/dd/yyyy)";
			appendToErrorList(errorList, errorMsg, idx, rowIds, rowNo);
		} catch (NullPointerException e) {
			if (validate) {
				errorMsg = " " + field;
				appendToErrorList(errorList, errorMsg, idx, rowIds, rowNo);
			}
		} catch (Exception e) {
			log(ERROR, "Exception occured while fetching Date cell value.");
		}

		return null;
	}

	private Boolean getBooleanValue(XSSFCell cell, List<String> errorList,
			int rowNo, Boolean validate, String field, Boolean isEmpty,
			HashSet<Integer> rowIds) {
		String errorMsg = "";
		int idx = rowIds.size() - 1;
		try {
			if (cell != null) {
				System.out.println("celltype" + cell.getCellType());
				isEmpty = false;
				if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
					System.out.println("CELL" + cell.getBooleanCellValue());
					return cell.getBooleanCellValue();
				} else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
					System.out.println("CELL" + cell.getStringCellValue());
					Boolean returnVal = false;
					if (cell.getStringCellValue() != null
							&& !cell.getStringCellValue().isEmpty()) {
						if (cell.getStringCellValue().equalsIgnoreCase("Yes")) {
							returnVal = true;
						} else {
							returnVal = false;
						}
					}
					// return new Boolean(cell.getStringCellValue());
					return returnVal;
				}

			}

		} catch (IllegalStateException exp) {
			errorMsg = " " + field;
			appendToErrorList(errorList, errorMsg, idx, rowIds, rowNo);
		} catch (NullPointerException e) {
			if (validate) {
				errorMsg = " " + field;
				appendToErrorList(errorList, errorMsg, idx, rowIds, rowNo);
			}
		} catch (Exception e) {
			log(ERROR, "Exception occured while fetching Date cell value.");
		}

		return null;
	}
}